package com.estate.web.controller.system;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.estate.common.annotation.Log;
import com.estate.common.core.controller.BaseController;
import com.estate.common.core.domain.AjaxResult;
import com.estate.common.core.domain.entity.SysRole;
import com.estate.common.core.domain.model.LoginUser;
import com.estate.common.core.domain.req.SysRoleAddReq;
import com.estate.common.core.domain.req.SysRoleEditReq;
import com.estate.common.core.domain.resp.SysRoleResp;
import com.estate.common.core.page.TableDataInfo;
import com.estate.common.enums.BusinessType;
import com.estate.common.enums.RoleTagEnum;
import com.estate.common.utils.StringUtils;
import com.estate.common.utils.bean.BeanUtils;
import com.estate.framework.web.service.SysPermissionService;
import com.estate.framework.web.service.TokenService;
import com.estate.system.service.ISysDeptService;
import com.estate.system.service.ISysRoleService;
import com.estate.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @GetMapping("/list")
    public TableDataInfo list(SysRole role)
    {
        startPage();
        Page<SysRole> list = roleService.selectRolePage(role);
        return getDataTable(list, SysRoleResp.class);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(roleId);
        SysRole sysRole = roleService.selectRoleById(roleId);
        return success(sysRole, SysRoleResp.class);
    }

    @GetMapping("/roleTagOptions")
    public AjaxResult roleTagOptions() {
        return success(Arrays.stream(RoleTagEnum.values()).map(RoleTagEnum::getTag).collect(Collectors.toList()));
    }

    /**
     * 新增角色
     */
    @Log(title = "Role Management", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRoleAddReq req)
    {
        SysRole role = new SysRole();
        BeanUtils.copyBeanProp(role, req);
        role.setDataScope(RoleTagEnum.getDataScopeByTag(req.getRoleTag()));
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("Failed to add role " + role.getRoleName() + ", role name already exists");
        }
        role.setCreateBy(getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @Log(title = "Role Management", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRoleEditReq req)
    {
        SysRole role = new SysRole();
        BeanUtils.copyBeanProp(role, req);
        // 设置 dataScope
        role.setDataScope(RoleTagEnum.getDataScopeByTag(req.getRoleTag()));

        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("Failed to update role " + role.getRoleName() + ", role name already exists");
        }
        role.setUpdateBy(getUsername());
        
        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("Failed to modify role " + role.getRoleName() + ", please contact the administrator");
    }

    /**
     * 状态修改
     */
    @Log(title = "Role Management", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @Log(title = "Role Management", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @GetMapping("/optionSelect")
    public AjaxResult optionSelect()
    {
        List<SysRoleResp> list = roleService.selectRoleAll().stream()
                .map(role -> {
                    SysRoleResp sysRoleResp = new SysRoleResp();
                    BeanUtils.copyBeanProp(sysRoleResp, role);
                    return sysRoleResp;
                })
                .collect(Collectors.toList());
        return success(list);
    }

}
